package chapter08

object Test02_MatchTypes {

  def main(args: Array[String]): Unit = {
    // 1.匹配常量
    def decribeConst(x: Any): String = x match {
      case 1 => "Num one"
      case "hello" => "String value"
      case true => "Boolean value"
      case '+' => "Char +"
      case _ => ""
    }

    // 2.匹配类型
    def describeType(x: Any): String = x match {
      case i: Int => s"Int $i"
      case s: String => s"String $s"
      case list: List[String] => s"List $list"
      case array: Array[Int] => s"Array ${array.mkString(">")}"
      case other => s"Something else:$other"
    }

    println(describeType(List("hi")))
    println(describeType(List(2324))) //会类型擦除
    println(describeType(Array(34)))
    println(describeType(Array("hihi"))) // 不会类型擦除

    println("====================")
    // 3.匹配数组
    for (arr <- List(Array(0),
      Array(0),
      Array(0, 1),
      Array(0, 1, 2),
      Array("hello", 1, 2),
      Array("33", 11, 2),
    )) {
      val result: String = arr match {
        case Array(0) => "0"
        case Array("hello", 1, 2) => "Array(\"hello\", 1, 2)"
        case Array(x, y) => s"Array:$x,$y" // 匹配两元素数组
        case Array(0, _*) => s"以0开头的数组"
        case Array(x, 1, z) => s"中间为1的三元素数组"
        case _ => "something else"
      }
      println(result)
    }


    println("====================")
    // 4.匹配列表
    for (arr <- List(Array(0),
      List(0),
      List("haha"),
      List(0, 1),
      List(0, 1, 2),
      List("hello", 1, 2),
      List("33", 11, 2),
    )) {
      val result: String = arr match {
        case List(0) => "0"
        case List("hello", 1, 2) => "Array(\"hello\", 1, 2)"
        case List(x, y) => s"List:$x,$y" // 匹配两元素数组
        case List(0, _*) => s"以0开头的数组"
        case List(x, 1, z) => s"中间为1的三元素List"
        case List(a) => s"一个元素的List:$a"
        case _ => "something else"
      }
      println(result)
    }

    println("====================")
    // 4.匹配列表 方式二
    val list = List(1, 3, 5, 7, 9)
    val list2 = List(100)

    list2 match {
      case first :: second :: rest => println(s"firse:$first,sesond:$second,rest:$rest")
      case _ => println("something else")
    }


    println("====================")
    // 5.匹配元组
    for (tuple <- List(
      (0, 1),
      (0, 0),
      (2, 1, 3),
      ("hello", true, 0.5),
    )) {
      val result =tuple match {
        case (a,b) => s"(${a},$b)"
        case (a,_) => s"(${a},_)"
        case (a,1,_) => s"(${a},1,_)"
        case (x,y,z) => "(x,y,z)"
        case _ => "something else"
      }
      println(result)
    }
  }
}
